<template>
  <div class="chart-item">
    <div :id="domId" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup>
import * as echarts from "echarts"
import { onMounted, watch, onUnmounted, nextTick } from 'vue'

const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({}),
  },
  chartType: {
    type: String,
    default: "line",
  },
  domId: {
    type: String,
    default: "ChartDom",
  },
})

let myChart = null

const initChart = () => {
  if (!props.chartData.xAxis || !props.chartData.series) {
    return
  }
  
  const chartDom = document.getElementById(props.domId)
  if (!chartDom) return
  
  // 先销毁旧图表
  if (myChart) {
    myChart.dispose()
  }
  
  myChart = echarts.init(chartDom)

  const series = props.chartData.series.map((item) => ({
    ...item,
    type: props.chartType,
    barWidth: props.chartData.barWidth || "16",
    itemStyle: {
      borderRadius: [15, 15, 0, 0],
    },
    smooth: true,
  }))

  // 计算Y轴范围
  const calculateYAxisRange = () => {
    let min = Infinity
    let max = -Infinity
    
    props.chartData.series.forEach(series => {
      series.data.forEach(value => {
        if (value !== null && !isNaN(value)) {
          min = Math.min(min, value)
          max = Math.max(max, value)
        }
      })
    })
    
    if (min === max) {
      min = min === 0 ? 0 : min * 0.9
      max = max === 0 ? 1 : max * 1.1
    }
    
    const range = max - min
    const padding = range * 0.05
    
    return {
      min: min - padding,
      max: max + padding,
      range
    }
  }

  const yAxisRange = calculateYAxisRange()
  const unit = props.chartData.unit || ''

  let option = {
    title: {
      text: props.chartData.title || "",
      left: "center",
      textStyle: {
        color: "#2979ff",
        fontSize: props.domId === 'zoomed-chart' ? 16 : 14
      },
    },
    color: ["#4dadf8", "#19be6b", "#ff9900", "#3d8a32", "#e8463a", "#ff4e3f"],
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "line"
      },
      formatter: (params) => {
        let result = `${params[0].axisValueLabel}<br/>`
        params.forEach(item => {
          const value = item.value === null ? '--' : item.value
          result += `${item.marker} ${item.seriesName}: ${value} ${unit}<br/>`
        })
        return result
      },
      confine: true
    },
    legend: {
      data: props.chartData.series.map((item) => item.name),
      icon: "rect",
      right: props.domId === 'zoomed-chart' ? 30 : 20,
      top: props.domId === 'zoomed-chart' ? 20 : 30,
      itemWidth: 14,
      itemHeight: 10,
      textStyle: {
        color: "#fff",
        fontSize: props.domId === 'zoomed-chart' ? 14 : 12
      },
    },
    grid: props.chartData.grid || {
      top: props.domId === 'zoomed-chart' ? 60 : 50,
      left: props.domId === 'zoomed-chart' ? 60 : 50,
      right: props.domId === 'zoomed-chart' ? 40 : 30,
      bottom: props.domId === 'zoomed-chart' ? 40 : 30,
      containLabel: true
    },
    xAxis: {
      type: "category",
      axisLine: {
        lineStyle: {
          color: "rgba(255,255,255,0.6)"
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: "rgba(255,255,255,0.8)",
        fontSize: props.domId === 'zoomed-chart' ? 14 : 12,
        interval: 0,
        rotate: props.domId === 'zoomed-chart' ? 0 : 30
      },
      data: props.chartData.xAxis
    },
    yAxis: [
      {
        type: "value",
        name: unit,
        nameLocation: "end",
        nameTextStyle: {
          color: "rgba(255,255,255,0.7)",
          padding: [0, 0, 0, 10],
          fontSize: props.domId === 'zoomed-chart' ? 14 : 12
        },
        min: yAxisRange.min,
        max: yAxisRange.max,
        interval: yAxisRange.range / 5,
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(255,255,255,0.6)"
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "rgba(255,255,255,0.1)"
          }
        },
        axisLabel: {
          color: "rgba(255,255,255,0.8)",
          fontSize: props.domId === 'zoomed-chart' ? 14 : 12,
          formatter: (value) => {
            if (Math.abs(value) >= 10000) {
              return (value / 10000).toFixed(1) + '万'
            } else if (Math.abs(value) >= 1000) {
              return (value / 1000).toFixed(1) + 'k'
            } else if (Math.abs(value) < 1 && value !== 0) {
              return value.toFixed(4)
            } else {
              return value.toFixed(yAxisRange.range > 100 ? 0 : 1)
            }
          }
        }
      }
    ],
    series: series,
    dataZoom: props.chartData.xAxis.length > (props.domId === 'zoomed-chart' ? 20 : 10) ? [{
      type: 'inside',
      start: 65,
      end: 100
    }] : []
  }

  myChart.setOption(option, true)
}

const resizeHandler = () => {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  if (myChart) {
    myChart.dispose()
  }
})

watch(
  () => props.chartData,
  () => {
    initChart()
  },
  { deep: true }
)

defineExpose({
  initChart
})
</script>

<style lang="scss" scoped>
.chart-item {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
</style>